package com.ewins.weatherdataclient.ui;

import com.ewins.weatherdatautils.bean.DownLoadFileInfo;
import com.ewins.weatherdatautils.bean.DownLoadState;
import com.google.common.eventbus.EventBus;
import org.apache.log4j.Logger;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceConfigurationError;

/**
 * Created by anzilu on 2016/3/7.
 */
public class SearchHistory implements Runnable{

    private boolean searchable;
    DateTimeFormatter dtf= DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    private String dbFileName;
    private DownLoadFileInfo downLoadHistory;
    List<DownLoadFileInfo> downLoadHistoryList = new ArrayList<DownLoadFileInfo>();
    EventBus eb;
    Logger logger=Logger.getLogger(SearchHistory.class);

    public SearchHistory(String dbFileName,EventBus eb){
        this.eb=eb;
        this.dbFileName=dbFileName;
    }
    @Override
    public void run() {
        searchable=true;
        while(searchable){

            searchHistoryList();
            try {
                Thread.sleep(5000);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //查询下载历史:下载历史,展示最近一天下载信息
    public synchronized void searchHistoryList(){
        try {
            Class.forName("org.sqlite.JDBC");
            Connection conn = DriverManager.getConnection("jdbc:sqlite:" + dbFileName);
            conn.setAutoCommit(true);
            Statement stmt = conn.createStatement();
            String sql="SELECT * from currentfile  WHERE  date(createtime)>= date('now'); ";
            String sqls="SELECT * from currentfile ";
            ResultSet rs = stmt.executeQuery(sqls);

            while(rs.next())
            {
                downLoadHistory=new DownLoadFileInfo();
                //downLoadHistory.setCategoryName(rs.getString(0));
                downLoadHistory.setFileName(rs.getString(1));
                downLoadHistory.setFilePriority(rs.getInt(2));
                downLoadHistory.setUrl(rs.getString(3));
                downLoadHistory.setCreatedTime(dtf.parseDateTime(rs.getString(4)));
                downLoadHistory.setCategoryName(rs.getString(5));
                downLoadHistory.setStartDownLoadTime(dtf.parseDateTime(rs.getString(6)));
                downLoadHistory.setState(DownLoadState.Finished);
                downLoadHistory.setLoadProgress("100%");
                downLoadHistoryList.add(downLoadHistory);
            }
            eb.post(downLoadHistoryList);
            rs.close();
            conn.close();
        }
        catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}
